import base64
import io
from typing import Optional

from PIL import Image
from nicegui import ui
import requests

# 配置DeepSeek API密钥和端点 (请替换为实际的API信息)
DEEPSEEK_API_KEY = "sk-fzaxlslrehzpfsrcdcadupnqkyrudlwodxircbjchaggxrfd"
DEEPSEEK_API_ENDPOINT = "https://api.siliconflow.cn/v1"


async def upload_handler(e):
    """处理图片上传"""
    try:
        # 清除之前的结果
        result_text.set_text("正在处理图片...")

        # 获取上传的文件
        upload = e.uploaded_files[0]

        # 读取图片内容
        with open(upload.name, "rb") as f:
            image_bytes = f.read()

        # 显示上传的图片
        image_base64 = base64.b64encode(image_bytes).decode("utf-8")
        image_display.set_source(f"data:image/jpeg;base64,{image_base64}")

        # 调用DeepSeek API解析经纬度
        response = await call_deepseek_api(image_bytes)

        if response and "latitude" in response and "longitude" in response:
            result_text.set_text(
                f"解析结果:\n纬度: {response['latitude']}\n经度: {response['longitude']}"
            )
        else:
            result_text.set_text("无法从图片中解析出经纬度信息")

    except Exception as ex:
        result_text.set_text(f"处理出错: {str(ex)}")


async def call_deepseek_api(image_bytes: bytes) -> Optional[dict]:
    """调用DeepSeek API解析图片中的经纬度"""
    try:
        # 准备请求头和数据
        headers = {
            "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
            "Content-Type": "application/json",
        }

        # 将图片转换为base64
        image_base64 = base64.b64encode(image_bytes).decode("utf-8")

        payload = {"image": image_base64, "features": ["geolocation"]}

        # 发送请求
        response = requests.post(DEEPSEEK_API_ENDPOINT, headers=headers, json=payload)
        response.raise_for_status()

        # 解析响应
        data = response.json()
        if "geolocation" in data:
            return data["geolocation"]

        return None

    except requests.exceptions.RequestException as e:
        print(f"API请求失败: {e}")
        return None
    except Exception as e:
        print(f"处理API响应失败: {e}")
        return None


# 创建UI界面
with ui.column().classes("w-full items-center"):
    ui.label("图片经纬度解析工具").classes("text-2xl font-bold")

    # 图片上传组件
    upload = (
        ui.upload(label="选择图片", auto_upload=True, on_upload=upload_handler)
        .props('accept="image/*"')
        .classes("w-64")
    )

    # 显示上传的图片
    image_display = ui.image().classes("max-w-md max-h-64")

    # 显示结果
    result_text = ui.label("等待上传图片...").classes("text-lg whitespace-pre")

# 运行应用
ui.run(title="图片经纬度解析", port=8080)
